package com.itheima.controller;

import com.aliyuncs.exceptions.ClientException;
import com.itheima.utils.SMSUtils;
import com.itheima.utils.ValidateCodeUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@CrossOrigin
@RequestMapping("/creatCode")
public class CreatCodeController {

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 生成验证码
     * @param info
     * @return
     */
    @PostMapping("/validCode")
    public Map validCode(@Param("info") String info){
        if (info==null){
            throw new RuntimeException("手机号为空");
        }
        //生成6位的验证码
        String validCode = ValidateCodeUtils.generateValidateCode4String(6);
        //发送短信
        try {
            SMSUtils.sendShortMessage(SMSUtils.VALIDATE_CODE,info,validCode);

            //发送成功将验证码存入redis
            redisTemplate.opsForValue().set("VALIDATE_CODE",validCode,300,TimeUnit.SECONDS);

            //封装返回数据
            Map result=new HashMap();
            result.put("code","success");
            result.put("data","生成验证码成功");
            return result;
        } catch (ClientException e) {
            e.printStackTrace();

            //封装返回数据
            Map result=new HashMap();
            result.put("code","error");
            result.put("data","生成验证码失败");
            return result;
        }
    }
}
